import json

from flask import Blueprint, request
from flask_restful import Resource, reqparse

from common import Result
from xtoad.auth.auth import generate_token
from xtoad.services.user import UserService

user_bp = Blueprint('user', __name__)

userService = UserService()


class UserApi(Resource):

    def get(self, id):
        data = userService.get(id)

        return Result.success(data)

    def post(self):
        # data = json.dumps(request.get_json(force=True))
        data = request.get_json(force=True)

        return Result.success(userService.add(data))

    def put(self, id):
        user = request.get_json(force=True)
        return Result.success({'put': {'id': id, 'user': user}})

    def delete(self, id):
        userService.delete(id=id)
        return Result.success({'delete': id})


class UserListApi(Resource):

    def get(self):
        data = userService.get_all()

        return Result.success(data)

    def post(self):
        data = request.get_json(force=True)

        return Result.success(userService.add_all(data))

    def put(self):
        user = request.get_json(force=True)
        Result.success({'put': {'id': id, 'user': user}})

    def delete(self, id):
        Result.success({'delete': id})


class LoginApi(Resource):

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True, location='json', help='用户名不能为空')
        parser.add_argument('pwd', type=str, required=True, location='json', help='密码不能为空')
        args = parser.parse_args()
        username = args['username']
        pwd = args['pwd']
        user = userService.get_by_username(username)
        if user:
            # 校验密码
            if user.verify_password(password=pwd):
                token = generate_token(user=user.id)
                return Result.success(message='登录成功', data={'token': token})

        return Result.faild(401, '用户名或者密码错误')
